import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../network/Api.dart';
import '../utils/loading.dart';

//查找好友
class SearchMember extends StatefulWidget {
  Function? refreshBlock;

  SearchMember({this.refreshBlock, Key? key}) : super(key: key);

  @override
  State<SearchMember> createState() => _SearchMemberState();
}

class _SearchMemberState extends State<SearchMember> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _messController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool canSend = false;
  bool send = false;
  late String centext;

  Map _userInfo = {};

  void validateInput(String test) {
    setState(() {
      canSend = test.isNotEmpty;
      centext = test;
    });
  }

  // 查询好友信息
  _getUserinfo(String string) async {
    // if (widget.easeuserId.isEmpty) return;
    final res = await Api.getInstance().queryUserInfo(string);
    final data = res['data'];
    if (data != null) {
      setState(() {
        _userInfo = data;
        send = true;
      });
    } else {
      toast(res['msg']);
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  // 添加环信用户信息
  _addUserinfo(String string) async {
    // if (widget.easeuserId.isEmpty) return;
    final res = await Api.getInstance().addUserInfo(string);
    final data = res['data'];
    if (res["code"] == 0) {
      toast(res['msg']);
      if (widget.refreshBlock != null) {
        widget.refreshBlock!();
      }
      setState(() {
        send = false;
      });
    } else {
      toast(res['msg']);
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(
            height: 20,
          ),
          Flexible(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Form(
                    key: _formKey,
                    child: SizedBox(
                      width: size.width - 80,
                      height: 40,
                      child: TextFormField(
                          autofocus: false,
                          maxLines: 3,
                          controller: _messController,
                          focusNode: _focusNode,
                          onChanged: validateInput,
                          keyboardType: TextInputType.text,
                          decoration: const InputDecoration(
                            isCollapsed: true,
                            fillColor: Color(0xffF1F3FB),
                            filled: true,
                            hintText: "请输入商圈ID",
                            prefixIcon: Icon(
                              Icons.search,
                              size: 20,
                              color: Colors.grey,
                            ),
                            contentPadding: EdgeInsets.only(left: 5, top: 10),
                            enabledBorder: OutlineInputBorder(
                              /*边角*/
                              borderRadius: BorderRadius.all(
                                Radius.circular(30), //边角为30
                              ),
                              borderSide: BorderSide(
                                color: Colors.white54, //边线颜色为黄色
                                width: 1, //边线宽度为2
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(
                                  Radius.circular(30), //边角为30
                                ),
                                borderSide: BorderSide(
                                  color: Colors.white54, //边框颜色为绿色
                                  width: 1, //宽度为5
                                )),
                          )),
                    )),
                Offstage(
                  offstage: !canSend,
                  child: InkWell(
                    onTap: () {
                      if (canSend) {
                        _getUserinfo(centext);
                      }
                    },
                    child: Container(
                      margin: const EdgeInsets.only(left: 10),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 5),
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5)),
                          color: ThemeColor.colorCF8F23),
                      child: const Text(
                        '搜索',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Offstage(
            offstage: !send,
            child: Container(
              margin: const EdgeInsets.only(top: 10),
              // padding: const EdgeInsets.only(left: 16, top: 11, bottom: 10,right: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Flexible(
                      child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: 15),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(5),
                          child: CachedNetworkImage(
                            imageUrl: Provider.fixAvatar(
                                _userInfo['profilePhoto'] ?? ""),
                            width: 40,
                            height: 40,
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 12,
                      ),
                      Text(
                        _userInfo['nickName'] ?? "",
                        style: const TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                            fontWeight: FontWeight.normal),
                      ),
                      const Expanded(child: Text("")),
                    ],
                  )),
                  InkWell(
                    onTap: () {
                      if (_userInfo['easeuserId'].toString().isNotEmpty) {
                        _addUserinfo(_userInfo['easeuserId'].toString());
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 5),
                      margin: const EdgeInsets.only(right: 12, left: 5),
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5)),
                          color: ThemeColor.colorCF8F23),
                      child: const Text(
                        '添加',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
